package com.anxin.registerManagement.service;

import cn.hutool.core.util.ObjectUtil;
import com.anxin.registerManagement.bean.dto.RoleDto;
import com.anxin.registerManagement.bean.jo.RoleSearchJo;
import com.anxin.registerManagement.bean.persist.PermissionGroup;
import com.anxin.registerManagement.bean.persist.Role;
import com.anxin.registerManagement.bean.persist.relation.RolePermissionGroupRelation;
import com.anxin.registerManagement.mapper.PermissionGroupMapper;
import com.anxin.registerManagement.mapper.RoleMapper;
import com.anxin.registerManagement.mapper.relation.RolePermissionGroupRelationMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 叶前呈
 * @date 2022/1/30 15:18
 */
@Service
public class RoleServcie {

    private static Logger logger = LoggerFactory.getLogger(RoleServcie.class);

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    PermissionGroupMapper permissionGroupMapper;

    @Autowired
    RolePermissionGroupRelationMapper rolePermissionGroupRelationMapper;

    /**
     * 查询角色
     */
    public PageInfo<RoleDto> getRoleList(RoleSearchJo roleSearchJo) {
        // 这里，如果没有传pageNum和pageSize则查询的是所有数据！
        if (!ObjectUtil.isEmpty(roleSearchJo.getPageNum()) && !ObjectUtil.isEmpty((roleSearchJo.getPageSize()))) {
            PageHelper.startPage(roleSearchJo.getPageNum(), roleSearchJo.getPageSize());
        }
        // 查询出所有角色
        List<RoleDto> roleDtoList = roleMapper.getRoleList(roleSearchJo);
        for (RoleDto roleDto : roleDtoList) {
            // 通过角色id获取所有权限组id
            QueryWrapper<RolePermissionGroupRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("permission_group_id").eq("role_id", roleDto.getId());
            List<Object> permissionGroupIdList = rolePermissionGroupRelationMapper.selectObjs(queryWrapper);
            // TODO:这里通过stream，将list类型转换
            List<Integer> idList = permissionGroupIdList.stream().map(per -> (Integer) per).collect(Collectors.toList());
            // 通过权限组id获取权限组集合
            List<PermissionGroup> permissionGroupList = permissionGroupMapper.selectBatchIds(idList);
            roleDto.setPermissionGroupList(permissionGroupList);
        }
        return new PageInfo<>(roleDtoList);
    }


    /**
     * 添加角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void addRole(RoleDto roleDto) {
        // TODO：判断是否为其他，是其他则输入其他
        // TODO:1.角色名称和角色代号分别校验，都需要唯一，2.权限组是否存在
        // 添加角色
        if(roleDto.getRoleName().equals("其他")){
            roleDto.setRoleName(roleDto.getCustomRoleName());
        }
        roleMapper.insert(roleDto);
        // 添加角色-权限组-关系
        addrolePermissionGroupRelation(roleDto.getId(),roleDto.getPermissionGroupIdList());
    }

    /**
     * 修改角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RoleDto roleDto) {
        // TODO:数据校验未做，1.角色名称和角色代号分别校验，都需要唯一2.角色是否存在，3.权限组是否存在，
        // 更新角色
        roleMapper.updateById(roleDto);
        // 删除角色-权限组-关系
        Map<String,Object> map = new HashMap<>();
        map.put("role_id",roleDto.getId());
        rolePermissionGroupRelationMapper.deleteByMap(map);
        // 添加角色-权限组-关系
        addrolePermissionGroupRelation(roleDto.getId(),roleDto.getPermissionGroupIdList());
    }

    /**
     * 删除角色
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(List<Integer> id) {
        // TODO:查看用户是否有关联角色，如果有，则不允许删除
        // 删除角色
        roleMapper.deleteBatchIds(id);
        // 删除角色-权限-关系
        QueryWrapper<RolePermissionGroupRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",id);
        rolePermissionGroupRelationMapper.delete(queryWrapper);
    }

    /**
     * 添加角色-权限组-关系
     */
    public void addrolePermissionGroupRelation(int roleId,List<Integer> permissionGroupIdList){
        for (Integer integer : permissionGroupIdList) {
            RolePermissionGroupRelation relation = new RolePermissionGroupRelation();
            relation.setRoleId(roleId);
            relation.setPermissionGroupId(integer);
            rolePermissionGroupRelationMapper.insert(relation);
        }
    }


}
